package controller

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"yak.admin/src/entity"
	"yak.admin/src/middleware"
	"yak.admin/src/module/backend/admin/form"
	"yak.admin/src/util"
)

func UploadAvatar(c *gin.Context) {
	var profile form.ProfileForm
	if filename, ok := profile.UploadAvatar(c); ok {
		middleware.ResultSuccess(c,"", map[string]interface{}{ "filename": filename })
		return
	}
	middleware.ResultFail(c,"头像保存失败", nil)
}

func UpdatePassword(c *gin.Context)  {
	var password form.PasswordForm
	if err := password.UpdatePassword(c); err != nil {
		middleware.ResultFail(c, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(c, "更新成功", nil)
}

func Profile(c *gin.Context) {
	var profile form.ProfileForm
	if err := profile.Save(c); err != nil {
		middleware.ResultFail(c, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(c, "更新成功", nil)
}

func SuperCreate(c *gin.Context) {
	f := form.AdminForm{Group: entity.AdminSuper}
	if _, err := f.CreateSuper(c); err != nil {
		middleware.ResultFail(c, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(c, "", nil)
}

func NormalCreate(c *gin.Context) {
	admin := c.MustGet(util.AdminKey).(entity.Admin)
	f := form.AdminForm{Group: entity.AdminNormal}
	if _, err := f.CreateNormal(c, admin.Type); err != nil {
		middleware.ResultFail(c, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(c, "", nil)
}

func ResetPassword(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	_ = form.ResetDefaultPassword(c, id)
	middleware.ResultSuccess(c, "重置密码成功！", nil)
	/*id, _ := strconv.Atoi(c.Query("id"))
	if err := form.ResetDefaultPassword(c, id); err != nil {
		middleware.ResultFail(c, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(c, "重置密码成功！", nil)*/
}

func DeleteAdmin(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	admin := c.MustGet(util.AdminKey).(entity.Admin)
	if admin.Id == id {
		middleware.ResultFail(c, "禁止删除自己", nil)
		return
	}

	if err := form.DeleteAdmin(c, id); err != nil {
		middleware.ResultFail(c, err.Error(), nil)
		return
	}
	middleware.ResultSuccess(c, "", nil)
}
